function [TransMat, EP] = EstTransMat_nonparam (bin_price, bin_lower, bin_upper, Pt, It, Pbint, P,I)
% Description:
%   This function estimates the price transition probabilites for each 
%   lagged price and interval. They are estimated using the observed 
%   continuous prices as opposed to the discretized prices. The price 
%   transition probabilites are between discretized prices. 
% PARAMETERS:
%   P = the number of price bins
%   I = the number of intervals
%   bin_price = the mean price of each defined price bin Px1(mean taken from observed price vector)
%   bin_lower = the lower price in each defined price bin Px1
%   bin_upper = the upper price in each defined price bin Px1
% All information is sorted from lowest bin to highest bin
%
% DATA:
%    Pt = the continuous price in each period
%    It = interval in each period
%    Pbint = the bin number of each price in each period ( actually not needed)
% Data is sorted by date and interval, that is they are sorted in the order
% in which they happened


disp ('START transition matrix - nonparametric specfication')
% get the number of observations
T = size(Pt,1);

% look at the next P
%Pnext = Pt([ 2:end  1]);
Pbintnext = Pbint([ 2:end  1]);

% lop off last obs
%Pt = Pt(1:(T-1),1);
%Pnext = Pnext(1:(T-1),1);
Pbint = Pbint(1:(T-1),1);
Pbintnext = Pbintnext(1:(T-1),1);
It = It(1:(T-1),1);
size(It);

TransMat = zeros(P,P,I);
EP=0;
% index = find(It==1 & Pbint==2 & Pbintnext==3)
% x = [Pbint(1:100),Pbintnext(1:100)]
% index = find(It==1 & Pbint==3 & Pbintnext==3)
index = find(It==8 & Pbint==5 );
[Pbintnext(index),Pbint(index)];
for i=1:I
   for pt = 1:P
       %i
       %pt
        for pt1 =1:P            
            
          index = find(It==i & Pbint==pt & Pbintnext==pt1);
          count=size(index,1); %count how many transitions there are
          TransMat(pt,pt1,i)=count;
          
        end
        denom=sum(TransMat(pt,:,i),2); %the number of transistions in observed for price and interval
        if denom>0                 
            TransMat(pt,:,i)= TransMat(pt,:,i)./denom; %normalize the transistion counts to probabilities
        elseif denom==0
            %TransMat(pt,:,i)=ones(1,P).*(1/P); % equal probability of each cell if the transition is never seen
            TransMat(pt,:,i)=zeros(1,P); % zero probabilit of each cell if the transition is never seen
        else
            display('Error in EstTransMat_nonparam.m')
            break
        end
   end
    TransMat(:,:,i);
end
format short
TransMat(1:10,1:10,8);

sum(sum(sum(TransMat,1),2),3);
% this should sum to 2207 which is the size of the vector, but I only get
% 2205, where did the other two obs go? am I doing something wrong?

disp ('END transition matrix - nonparametric specfication')

end
